// pages/shop/platform.js
var app = getApp();
var currentPage = 1;
var currentShopId;
var tid;
var sort = 0;
Page({
    data: {
        categories_actice: 0,
        categories: [],
        products: [],
        is_search: false,
        is_open: false,
        showModalStatus: false,
    },
    onShow: function () {
        if (this.data.categories.length > 0) {
            this.categoriesReload();
        }
    },
    powerDrawer: function () {
        this.util('close');
     // this.setData({
     //    showModalStatus:0,
     // })
     }, 
     util: function(currentStatu){ 
     /* 动画部分 */ 
     // 第1步：创建动画实例 
         var animation = wx.createAnimation({ 
         duration: 200, //动画时长 
         timingFunction: "linear", //线性 
         delay: 0 //0则不延迟 
         }); 
     // 第2步：这个动画实例赋给当前的动画实例 
        this.animation = animation; 
     // 第3步：执行第一组动画 
        animation.opacity(0).rotateX(-100).step(); 
     // 第4步：导出动画对象赋给数据对象储存 
        this.setData({ 
            animationData: animation.export() 
        }) 
     // 第5步：设置定时器到指定时候后，执行第二组动画 
        setTimeout(function () {
         // 执行第二组动画 
            animation.opacity(1).rotateX(0).step(); 
         // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象 
            this.setData({ 
                animationData: animation 
            }) 
         
         //关闭 
            if (currentStatu == "close") { 
                this.setData({ 
                 showModalStatus: false 
                }); 
            } 
        }.bind(this), 200) 
     // 显示 
            if (currentStatu == "open") { 
                this.setData({ 
                  showModalStatus: true 
                }); 
            } 
        },
    bindChange: function(e) {
        sort = e.detail.value[0];
    },

    onReady: function () {
        // 页面渲染完成
        var that = this;
        var shop = wx.getStorageSync('shop');
        currentShopId = shop.id;
        that.getShopInfo(currentShopId);

        that.categoriesReload();
    },
    //获取当前当前店铺指定分类下的商品列表
    getproducts: function (cateId) {

        console.log("currentPage:" + currentPage);
        var that = this;
        that.setData({
            loadMore: false
         })
        wx.showLoading({ title: '数据加载中...', mask: true });
        app.func.req('products/index', {
            is_platform: true,
            product_cate_id: cateId,
            page_index: currentPage,
            page_size: 10
        }, 'GET', function (res) {
            console.log(res);
            if(res.code == "error" && res.result.type=='down'){
                wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000,
                    mask:false
                })
                return;
              }
            if (res.code == "success") {
                var products = app.util.convertProducts(res.result);
                var currentProducts = that.data.products.concat(products);
                that.setData({
                    loadMore: true,
                    products: currentProducts
                });
                //购物车信息加到商品中
                currentPage++;
            }
            wx.hideLoading();
        }, {
                'token': wx.getStorageSync('token')
            });
    },
    loadMore: function () {
        var that = this;
        if (that.data.loadMore) {
            that.getproducts(that.data.categories[that.data.categories_actice].id);
        }
    },
    //分类切换
    categorySelect: function (e) {
        var that = this;
        var index = e.target.dataset.index;
        var new_categories = this.data.categories;
        var old_active = this.data.categories_actice;
        var new_active = index;
        new_categories[old_active].active = false;
        new_categories[index].active = true;
        this.setData({
            categories: new_categories,
            categories_actice: new_active,
            products: []
        })
        //获取商品列表
        currentPage = 1;
        that.getproducts(new_categories[index].id);
    },
    closeModal: function () {
        this.setData({
            showModal: false
        })
    },
    formsubmit:function(e){
        var that = this;        
        var productId = that.data.productId;
        var shop_categories = that.data.shop_categories;
        var category_id = shop_categories[sort].id;

        var limit_depot = that.data.limit_depot;
        var count_num = that.data.count_num;
        

        if(limit_depot!=0 && limit_depot*1000 < new Date()){
            wx.showToast({
              title: '限时入库已到期',
              icon: 'info',
              duration: 3000
            })
            return; 
        }

        app.func.req('shops/proxy_product', { 
            id: productId,
            category_id: category_id,
        }, 'POST', function (res) {
            if (res.code == "success") {
              that.util('close');
                wx.showModal({
                    title: '提示',
                    content: '入库成功，请在商品页面查看',
                })
            } else {
                var content = '入库失败'
                if (res.msg == "product.proxy.exist") {
                    content += '，商品已存在'
                }
                if (res.msg == "product.time.expired") {
                    content += '，限时商品已过期'
                }
                wx.showModal({
                    title: '提示',
                    content: content,
                })
            }
        }, {
                'token': wx.getStorageSync('token')
            });

        
    }, 
    productDo: function (e) {
        var productId = e.target.dataset.id;
        var id = e.target.dataset.id;
        var index = e.target.dataset.index;
        var that = this;
        var shop_category_names = this.data.shop_category_names;
        var shop_categories = this.data.shop_categories;
        if (!shop_category_names || shop_category_names.length == 0) {
            wx.showModal({
                title: '提示',
                content: '请先在货架页添加平台商品分类',
            })
            return false;
        }
        console.log(e.currentTarget.dataset.time);
        that.setData({
            nickname:e.currentTarget.dataset.nickname,
            productId:productId,
            limit_depot:e.currentTarget.dataset.time,
            count_num:e.currentTarget.dataset.num,
        })
        var currentStatu = e.currentTarget.dataset.statu; 
        this.util(currentStatu);
        // wx.showActionSheet({
        //     itemList: shop_category_names,
        //     success: function (res) {
        //         if (res.tapIndex < shop_category_names.length) {
                    
        //             app.func.req('shops/proxy_product', {
        //                 id: productId,
        //                 category_id: shop_categories[res.tapIndex].id
        //             }, 'POST', function (res) {
        //                 if (res.code == "success") {
        //                     wx.showModal({
        //                         title: '提示',
        //                         content: '入库成功，请在商品页面查看',
        //                     })
        //                 } else {
        //                     var content = '入库失败'
        //                     if (res.msg == "product.proxy.exist") {
        //                         content += '，商品已存在'
        //                     }
        //                     wx.showModal({
        //                         title: '提示',
        //                         content: content,
        //                     })
        //                 }
        //             }, {
        //                     'token': wx.getStorageSync('token')
        //                 });
        //         }
        //     }
        // })
    },
    setSearch: function (e) {
        var that = this; 
        this.setData({
            searchName: e.detail.value,
        });
        //clearTimeout(tid);
        //if (e.detail.value.length > 0) {
        //  tid = setTimeout(function () {
        //    that.searchProduct();
        //  }, 500);
        //} else {
        //  this.searchCancel();
        //}
    },
    searchProduct: function () {
        var that = this;
        var name = this.data.searchName;
        currentPage = 1;
        wx.showLoading({ title: '数据加载中...', mask: true });
        app.func.req('products/index', {
            is_platform: true,
            name: name
        }, 'GET', function (res) {
            console.log(res)

            var products = res.result;
            that.setData({
                loadMore: false,
                products: products,
                is_search: true
            });

            wx.hideLoading();
        }, {
                'token': wx.getStorageSync('token')
            });
    },
    searchCancel: function (e) {
        this.setData({
            is_search: false,
            products: [],
            searchName: null
        });
        this.getproducts(this.data.categories[this.data.categories_actice].id);
    },
    getShopInfo: function (shopId) {
        var that = this;
        app.func.req('shops/info', {
            id: shopId
        }, 'GET', function (res) {
            if (res.code == "success") {
                if (res.result.lib_status == '1') {
                    that.setData({
                        is_open: true
                    });
                } else {
                    that.setData({
                        is_open: false
                    });
                }
            }
        }, {
                'token': wx.getStorageSync('token')
            });
    },
    categoriesReload: function () {
        var that = this;
        app.func.req('product_cates/index', { shop_id: currentShopId, is_platform: true }, 'GET', function (res) {
            var index = that.data.categories_actice;
            var cateId = res.result.platform[0].id;
            var categories = app.util.covertProductCates(res.result.platform);
            var shop_categories = res.result.shop;
            categories[0].active = true;
            if (that.data.categories.length > 0) {
                var oldCategories = that.data.categories;
                var oldCateId = oldCategories[index].id;

                for (var i = 0; i < categories.length; i++) {
                    if (categories[i].id == oldCateId) {
                        categories[i].active = true;
                        cateId = oldCateId;
                    } else {
                        categories[i].active = false;
                    }
                }
            }
            var names = [];
            if (shop_categories && shop_categories.length > 0) {
                shop_categories.forEach(function (cate) {
                    names.push(cate.name);
                })
            }
            that.setData({
                categories: categories,
                shop_categories: shop_categories,
                shop_category_names: names
            });
            // 获取该分类下的商品列表
            that.getproducts(cateId);
        }, {
                'token': wx.getStorageSync('token')
            });
    },
})